<template>
  <div class="wrap">
    <h2>嗨购管理后台系统</h2>
    <el-form :rules="rules" :model="loginForm">
      <el-form-item prop="adminname">
        <el-input
          v-model="loginForm.adminname"
          placeholder="请输入管理员账号"
          :prefix-icon="User"
        />
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="loginForm.password"
          placeholder="请输入密码"
          :prefix-icon="Lock"
          type="password"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" style="width: 100%" @click="login"
          >登录</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { useRouter } from "vue-router";
import { User, Lock } from "@element-plus/icons-vue";
import { loginApi } from "../../api/admin";
import { ElMessage } from "element-plus";

// 一般表单绑定的时候用reactive
import { reactive } from "vue";

import type { FormRules } from "element-plus";

import { useHomeStore } from "../../stores/home";

const homeStore = useHomeStore();

interface FormType {
  adminname: string;
  password: string;
}

const loginForm = reactive<FormType>({
  adminname: "",
  password: "",
});

const rules = reactive<FormRules>({
  adminname: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [
    {
      required: true,
      message: "请输入密码",
      trigger: "blur",
    },
    { min: 3, max: 10, message: "密码长度不对", trigger: "blur" },
  ],
});

const router = useRouter();

const login = async () => {
  try {
    const res: any = await loginApi(loginForm);
    ElMessage({
      message: res.message,
      type: "success",
    });

    homeStore.changeLoginInfo({
      name: res.data.adminname,
      token: res.data.token,
      checkedkeys: JSON.stringify(res.data.checkedkeys),
    });
    localStorage.setItem("adminname", res.data.adminname);
    localStorage.setItem("token", res.data.token);
    localStorage.setItem("checkedkeys", JSON.stringify(res.data.checkedkeys));

    router.push("/");
  } catch (err) {
    return err;
  }
};
</script>

<style lang="less" scoped>
.wrap {
  margin: 150px auto;
  width: 400px;

  h2 {
    text-align: center;
    margin-bottom: 50px;
    font-size: 30px;
  }
}
</style>
